﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Catering.View_Operaction;
using System.Text;
using System.Collections;

namespace Catering.Catering_Page.Kufang
{
    public partial class Ckgl_ImportExcel : UserIsNull
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.txt_addtime.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy/MM/dd',maxDate:'%y-%M-%d'})");
            if (!IsPostBack)
            {
                string groupid = "";
                string classid = "";
                if (Request.QueryString["GroupID"] != null) groupid = Request.QueryString["GroupID"].ToString();
                if (Request.QueryString["ClassID"] != null) classid = Request.QueryString["ClassID"].ToString();
                this.HFGroupID.Value = groupid;
                this.HFClassID.Value = classid;
            }
        }

        //导入Excel
        protected void BT_daoru_Click(object sender, EventArgs e)
        {
            if (this.HFGroupID.Value == "" || this.HFClassID.Value == "")
            {
                View_Operaction_Common.Show(this, "您的操作有误，请返回重新操作！");
                return;
            }
            if (this.FileUpload1.FileName != null && this.FileUpload1.FileName.Length > 0)
            {
                List<int> inspetion = new List<int>();
                inspetion.Add(3);
                inspetion.Add(6);
                DataSet ds = View_Operaction_Excel.exceltodataset(new DataBase_Manage_Operaction().UpFile(this.FileUpload1), inspetion, 4);
                if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0] != null)
                {
                    this.IsYanzhen.Value = "true";//验证数据是否全部符合要求
                    DataTable newdt = this.ExcelToDataTable(ds.Tables[0]);//合并相同品号的数据
                    if (newdt != null && newdt.Rows.Count > 0)
                    {
                        Session["ExcelInfo"] = newdt;
                        Repeater1.DataSource = newdt;
                        //进行数据绑定
                        Repeater1.DataBind();
                        TB_baocun.Enabled = true;
                    }
                }
            }
        }

        //读取Excel数据并验证
        private DataTable ExcelToDataTable(DataTable dt_import)
        {
            DateTime AddDate = DateTime.Now;
            int TempClassid = 0;
            if (!string.IsNullOrEmpty(this.txt_addtime.Text))
            {
                DateTime.TryParse(this.txt_addtime.Text, out AddDate);
                AddDate = new DateTime(AddDate.Year, AddDate.Month, AddDate.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            }
            if (this.HFGroupID.Value == "" || this.HFClassID.Value == "")
            {
                View_Operaction_Common.Show(this, "您的操作有误，请返回重新操作！");
                return null;
            }
            else
            {
                Int32.TryParse(this.HFClassID.Value, out TempClassid);
                if (TempClassid <= 0)
                {
                    View_Operaction_Common.Show(this, "您的操作有误，请返回重新操作！");
                    return null;
                }
            }

            DataTable dt = new DataTable();
            dt.Columns.Add("XuHao");
            dt.Columns.Add("Type1");
            dt.Columns.Add("Type2");
            dt.Columns.Add("InDBId");
            dt.Columns.Add("RawName");
            dt.Columns.Add("Price");
            dt.Columns.Add("Numbers");
            dt.Columns.Add("Balance");
            dt.Columns.Add("JingJieXian");
            dt.Columns.Add("CMP");
            dt.Columns.Add("YanZheng");
            dt.Columns.Add("AddDate");

            StringBuilder result = new StringBuilder("");
            string noindbid = "";//品号为空
            string nonumber = "";//数量为空或数量格式不正确
            string haveraw = "";
            int noindbidnum = 0;
            int nononumbernum = 0;
            int haverawnum = 0;

            int i = 1;
            foreach (DataRow dr_Temp in dt_import.Rows)
            {
                DataRow dr = dt.NewRow();
                if (dr_Temp == null) continue;
                decimal ImportNumber = 0;


                //品号是否为空
                if ((dr_Temp[3] == null || dr_Temp[3].ToString().Trim().Length == 0) && (dr_Temp[4] != null && dr_Temp[4].ToString().Trim().Length > 0))
                {
                    noindbid += dr_Temp[4].ToString().Trim() + "　";
                    noindbidnum++;
                    continue;
                }

                //数量是否正确
                if ((dr_Temp[6] == null || dr_Temp[6].ToString().Trim().Length == 0) && (dr_Temp[4] != null && dr_Temp[4].ToString().Trim().Length > 0))
                {
                    nonumber += dr_Temp[4].ToString().Trim() + "(" + dr_Temp[3].ToString() + ")　";
                    nononumbernum++;
                    continue;
                }

                Decimal.TryParse(dr_Temp[6].ToString().Trim(), out ImportNumber);

                if (ImportNumber <= 0)
                {
                    nonumber += dr_Temp[4].ToString().Trim() + "(" + dr_Temp[3].ToString() + ")　";
                    nononumbernum++;
                    continue;
                }

                string StrWhere = " ClassID=" + TempClassid + " AND InDBId='" + dr_Temp[3].ToString().Trim() + "' AND Year(AddDate)=" + AddDate.Year + " AND Month(AddDate)=" + AddDate.Month + " AND Day(AddDate)=" + AddDate.Day + " AND ChangeNumber=" + ImportNumber + " AND ChangeType=1 ";
                int count = new Catering_Rules.BalanceInfo().GetCount(StrWhere);
                if (count > 0)
                {
                    haveraw += dr_Temp[4].ToString().Trim() + "(" + dr_Temp[3].ToString() + ")　";
                    haverawnum++;
                    continue;
                }

                string type1 = dr_Temp[1].ToString().Trim();
                string type2 = dr_Temp[2].ToString().Trim();
                string indbid = dr_Temp[3].ToString().Trim();
                string rawName = dr_Temp[4].ToString().Trim();
                string price = dr_Temp[5].ToString().Trim();
                string numbers = dr_Temp[6].ToString().Trim();
                string balance = dr_Temp[7].ToString().Trim();
                string jjx = dr_Temp[8].ToString().Trim();
                string CMP = dr_Temp[9].ToString().Trim();

                //判断此品号的原料是否存在
                Catering_Model.RawMaterial_Area rarea = null;
                Catering_Model.E_RawMaterial rawmater = null;
                List<Catering_Model.RawMaterial_Area> rarealist = new Catering_Rules.RawMaterial_Area().GetModelList(" InDBId='" + indbid + "' ");
                if (rarealist != null && rarealist.Count > 0) rarea = rarealist[0];
                if (rarea != null) rawmater = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(rarea.RawID));
                if (rawmater == null)
                {
                    dr["XuHao"] = i;
                    dr["Type1"] = type1;
                    dr["Type2"] = type2;
                    dr["InDBId"] = indbid;
                    dr["RawName"] = rawName;
                    dr["Price"] = price;
                    dr["Numbers"] = numbers;
                    dr["Balance"] = balance;
                    dr["JingJieXian"] = jjx;
                    dr["CMP"] = CMP;
                    dr["YanZheng"] = "NoRaw";//没有此品号所对应的原料
                    dr["AddDate"] = AddDate;
                    dt.Rows.Add(dr);
                    i++;
                    if (this.IsYanzhen.Value == "true") this.IsYanzhen.Value = "false";
                    continue;
                }

                CMP = new Catering_Rules.Units().GetModel(Convert.ToInt32(rawmater.temp2)).UName;
                ArrayList al = new Catering_Rules.BalanceInfo().GetLastBalanceInfo(TempClassid.ToString(), rawmater.id.ToString(), indbid);
                if (al != null && al.Count >= 3) price = al[2].ToString();

                //获取可出库数量
                decimal sechbalance = new Catering_Rules.BalanceInfo().GetBalance(TempClassid, indbid, AddDate);
                if (ImportNumber > sechbalance)
                {
                    dr["XuHao"] = i;
                    dr["Type1"] = type1;
                    dr["Type2"] = type2;
                    dr["InDBId"] = indbid;
                    dr["RawName"] = rawmater.RAWName;
                    dr["Price"] = price;
                    dr["Numbers"] = numbers;
                    dr["Balance"] = sechbalance;
                    dr["JingJieXian"] = jjx;
                    dr["CMP"] = CMP;
                    dr["YanZheng"] = "PassBalance";//超过当时的可出库量
                    dr["AddDate"] = AddDate;
                    dt.Rows.Add(dr);
                    if (this.IsYanzhen.Value == "true") this.IsYanzhen.Value = "false";
                    i++;
                    continue;
                }

                
                dr["XuHao"] = i;
                dr["Type1"] = type1;
                dr["Type2"] = type2;
                dr["InDBId"] = indbid;
                dr["RawName"] = rawmater.RAWName;
                dr["Price"] = price;
                dr["Numbers"] = numbers;
                dr["Balance"] = sechbalance;
                dr["JingJieXian"] = jjx;
                dr["CMP"] = CMP;
                dr["YanZheng"] = "";//超过当时的可出库量
                dr["AddDate"] = AddDate;
                dt.Rows.Add(dr);
                i++;
            }
            if (!string.IsNullOrEmpty(nonumber)) result.Append("数量为0的数据(" + nononumbernum + ")：" + nonumber + "<br/>");
            if (!string.IsNullOrEmpty(noindbid)) result.Append("品号原料不存在的数据(" + noindbidnum + ")：" + noindbid + "<br/>");
            if (!string.IsNullOrEmpty(haveraw)) result.Append("已入库的数据(" + haverawnum + ")：" + haveraw + "<br/>");
            this.errordiv.InnerHtml = result.ToString();
            return dt;
        }

        //设置行颜色
        public string GetStyle(string strNumber)
        {
            string strBgC = string.Empty;
            switch (strNumber.Trim())
            {
                case "NoRaw"://没有原料 
                    strBgC = "background-color:red; height: 32px";
                    break;
                case "PassBalance"://超出可出库量
                    strBgC = "background-color:#AABFAA; height: 32px";
                    break;
            }
            return strBgC;
        }

        protected void TB_baocun_Click(object sender, EventArgs e)
        {
            if (this.IsYanzhen.Value != "true")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('存在不符合要求的数据！');</script>");
                return;
            }

            DataTable dt = Session["ExcelInfo"] as DataTable;
            if (dt != null && dt.Rows.Count > 0)
            {
                StringBuilder result = new StringBuilder("");
                string noraw = "";
                string error = "";
                //dt = this.ExcelToDataTable_Hebing(dt);//合并相同品号的数据
                foreach (DataRow dr in dt.Rows)
                {
                    string RawId = new Catering_Rules.RawMaterial_Area().GetList("InDBid='" + dr["InDBId"].ToString() + "'").Tables[0].Rows[0]["RawID"].ToString();
                    Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(Convert.ToInt32(RawId));
                    if (md_Raw == null || md_Raw.id <= 0)
                    {
                        noraw += dr["RawName"].ToString() + "(" + dr["InDBid"].ToString() + ")　";
                        continue;
                    }
                    Catering_Model.FromRecords md = new Catering_Model.FromRecords();
                    md.id = new Catering_Rules.FromRecords().GetMaxId();
                    md.GroupID = Convert.ToInt32(this.HFGroupID.Value);
                    md.ClassID = Convert.ToInt32(this.HFClassID.Value);
                    md.DBID = md_Raw.RAWTID;
                    md.RAWTID = md_Raw.RAWID;
                    md.RAWIDs = md_Raw.RAWIDS;
                    md.RAWID = md_Raw.id;
                    md.RAWName = md_Raw.RAWName;
                    md.Price = Convert.ToDecimal(dr["Price"]);
                    md.Numbers = dr["Numbers"].ToString();
                    md.AmountMoney = Convert.ToDecimal(md.Price * Convert.ToDecimal(dr["Numbers"].ToString()));
                    md.CMP = dr["CMP"].ToString();
                    md.OutDate = Convert.ToDateTime(dr["AddDate"].ToString());
                    md.Back = "";

                    md.Specifications = "";
                    md.InDBid = dr["InDBid"].ToString();
                    md.temp1 = "0";
                    md.temp2 = "";

                    decimal sum = Convert.ToDecimal(md.Numbers);//总重量
                    bool iskg = true;
                    decimal guige = 1;
                    decimal UtilKg = Toolss.GetSpecifications(Convert.ToInt32(md.RAWID), md.CMP, out iskg);
                    guige = iskg ? 1000 : 1;
                    decimal weight = Toolss.GetMathResult(UtilKg * sum, 2, 3);
                    md.SumNumber = weight * guige;

                    ArrayList cal = new Catering_Rules.FromRecords().CanbeFromRecords(md);
                    if (cal != null && cal[0].ToString() != "OK")
                    {
                        error += dr["RawName"].ToString() + "(" + dr["InDBid"].ToString() + ")　";
                    }
                    else
                    {
                        int result1 = new Catering_Rules.BalanceInfo().AddFromRecords(md_Raw.id, Convert.ToInt32(this.HFClassID.Value), md.InDBid, md.OutDate, md.Numbers, "", md.id);
                        if (result1 == 3)
                        {
                            new Catering_Rules.FromRecords().Add(md);
                        }
                        else
                        {
                            error += dr["RawName"].ToString() + "(" + dr["InDBid"].ToString() + ")　";
                        }
                    }
                }
                Session["ExcelInfo"] = null;
                if (!string.IsNullOrEmpty(noraw)) result.Append("原料不存在的数据：" + noraw);
                if (!string.IsNullOrEmpty(error)) result.Append("数量为0的数据：" + error);
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存成功！" + result.ToString() + "');window.location='Ckgl.aspx';</script>");
            }
            else
            {
                View_Operaction_Common.Show(this, "没有数据保存");
            }
        }
    }
}